import { setStorage, getStorage } from './bridge.js'

export const initResizable = () => {
  const list = [...document.querySelectorAll('.resizable-bar')]
  return Promise.all(list.map(async (el) => {
    const id = el.dataset.target
    const target = document.querySelector(id)
    const cacheId = `${id}-resize-width`
    const cache = await getStorage(cacheId)
    if (cache) {
      target.style.width = `${cache}px`
    }
    el.addEventListener('mousedown', (e) => {
      const startX = e.clientX
      const initWidth = target.offsetWidth
      const moveHandler = (e) => {
        const diffX = e.clientX - startX
        target.style.width = `${initWidth + diffX}px`
      }
      document.addEventListener('mousemove', moveHandler)

      document.addEventListener('mouseup', () => {
        setStorage(cacheId, target.offsetWidth)
        document.removeEventListener('mousemove', moveHandler)
      })
    })
  }))
}